<?php

/**
 *  进程详情（废弃可以删了）
 */

namespace app\api\controller;

use com\YHprobe;
use app\common\Script;
use app\common\controller\Common;

class Process  extends Common
{
    protected $state = [
        'D'=>'不可中断睡眠',
        'R'=>'运行',
        'S'=>'睡眠',
        'T'=>'已终止',
        'X'=>'已死',
        'Z'=>'已终止但还未被回收',
        '<'=>'高优先级',
        'N'=>'低优先级',
        'L'=>'页面锁定在内存',
        's'=>'含有子进程',
        'l'=>'多线程',
        '+'=>'位于前台进程组中'
    ];

    protected $process_server = [
        'fileManagement' => ['detail' => '文件管理服务' ,'name'=>'start.php'],
        'turningTrains_1' => ['detail' => '实时转写轮巡服务' ,'name'=>'TrainAuto_RaiSound_hw'],
        'turningTrains_2' => ['detail' => '非实时转写轮巡服务' ,'name'=>'Train_Vad'],
        'sendTransResult' => ['detail' => '实时转写结果发送服务' ,'name'=>'TransferServer.py']
    ];
    /**
     * 进程状态
     */
    public function processDetail($type = 1)
    {
        try{
            $cmd = "ps ax |grep online2-wav-nnet3-latgen-faster-tcp-part |grep -v grep|grep -v vi|grep -v dbx   |grep -v tail|grep -v start|grep -v stop |awk '{print $1}'";
            @exec($cmd,$pid_arr);
            if($type == 2)
            {
                $cmd = "top -b -n 1 |grep nnet3-lat|awk '{print $1}'";
                @exec($cmd,$pid2_arr);
                $pid_arr = array_diff($pid2_arr, $pid_arr);
            }
            if(empty($pid_arr))
            {
                return resultArray(['data' => []]);
            }
            while(NULL !== ($pid = array_pop($pid_arr)))
            {
                $data[] = YHprobe::getProcessInfo($pid);
            }
            foreach($data as &$value){
                $value['stat'] = $this->state[$value['stat']];
                $value['mem'] = round($value['mem'] / 1024, 2) . 'mb';
                $value['etime'] = trim($value['etime']);
                $value['cpu'] = trim($value['cpu']) . '%';
            }
            return resultArray(['data' => ['list'=>$data] ]);
        }catch(\Exception $e)
        {
            return resultArray(['error' => $e->getMessage()]);
        }
        
    }

    /**
     * 修改非实时进程的转写速度
     */
    public function accelerate()
    {
        $param = $this->param;
        if(!$param['multiple'] || $param['multiple'] > config('SERVER_KERNEL'))
        {
            return resultArray(['error' => '参数不正确']);
        }
        if($param['multiple'] != 1 && $param['multiple'] != 2 && $param['multiple'] != 4 && $param['multiple'] != 8)
        {
            return resultArray(['error' => '参数不正确']);
        }
        //修改转写的进程
        $i = $param['multiple'];
        $script = new Script();
        //$cmd = "sudo /home/speed_up_transfer.sh $i";
        //system($cmd);
        $script->nonrealTransformModification($i);

        $sys_model = Model('SystemConfig');
        $_off_num = $sys_model->get(['name' => 'OFFLINE_NUM']);
        $_off_num->value = $param['multiple'];
        $_off_num->save();
        return resultArray(['data' => '']);
    }

    /**
     * 进程监控
     */
    public function monitoredProcess(){
        $data = [];
        foreach($this->process_server as $key => $value){
            $cmd = "ps ax |grep ".$value['name']."|grep -v grep|awk '{print $1}'";
            $res = [];
            exec($cmd,$res);
            $pid_count = count($res);
            $data[] = [
                'server_name' => $key,
                'detail' => $value['detail'],
                'count' => $pid_count,
                'status' => $pid_count == 0 ? '异常' : ($pid_count == 1 ? '正常' : '多个'),
            ];
        }
        $result = [
            'list' => $data,
            'total' => count($data),
        ];
        return resultArray(['data' => $result]);
    }

}